package com.example.redis.service.impl;

import com.example.redis.service.INewsRedisService;
import com.example.service.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class NewsRedisServiceImpl implements INewsRedisService {

    private String prefix = "artical";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private INewsService newsService;

    @Override
    public long viewnumIncr(Long id) {
        String key = prefix+":"+id;
        Long res = redisTemplate.opsForValue().increment(key);
        return res;
    }

    @Override
    public boolean chijiuhua() {
        Set<String> keys = redisTemplate.keys(prefix+"*");
        for (String key : keys) {
            String viewnumStr = redisTemplate.opsForValue().get(key);
            Long viewnum = Long.parseLong(viewnumStr);
            String idstr = key.substring(key.indexOf(":") + 1);
            Long id = Long.parseLong(idstr);
            newsService.updateViewNum(id, viewnum);
        }
        return true;
    }
}
